package com.example.stlink.activitys.fragmentChild.activityStuClassList;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.example.stlink.R;
import com.example.stlink.configs.adapter.StuCourseSignedAdapter;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.domain.CourseSign;
import com.example.stlink.model.request.StuSignRequest;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.model.response.data.CourseData;
import com.example.stlink.utils.CommonUtils;
import com.example.stlink.utils.httpUtils.GetUrlParamHttpUtils;
import com.example.stlink.utils.httpUtils.PostBodyParamHttpUtils;
import com.google.android.material.textfield.TextInputEditText;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.util.ArrayList;
import java.util.List;

public class CourseSignIn extends AppCompatActivity {

    private ImageView abIvTitle;
    private TextView tvCreateTimeMsg;
    private TextView tvSignAddressMsg;
    private TextView tvCourseName;
    private Button btSign;
    private TextView tvSignRecord;
    private RecyclerView rvStuCourseList;

    private TextInputEditText etCodeInput;

    private static List<CourseSign> courseHasSignedList;
    @SuppressLint("StaticFieldLeak")
    private static StuCourseSignedAdapter adapter;

    private Handler signHandler;
    private Handler getSignedHandler;
    private Bundle bundle;

    private String signCodeStr;
    private long courseSignId;
    private long courseId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stu_course_sign_in);

        initView();
    }

    private void initView(){
        CommonUtils.changeStatusBar(CourseSignIn.this);

        abIvTitle = findViewById(R.id.ab_iv_title);
        tvCreateTimeMsg = findViewById(R.id.tv_create_time_msg);
        tvSignAddressMsg = findViewById(R.id.tv_sign_address_msg);
        tvCourseName = findViewById(R.id.tv_course_name);
        btSign = findViewById(R.id.bt_sign);
        tvSignRecord = findViewById(R.id.tv_sign_record);
        rvStuCourseList = findViewById(R.id.rv_stu_course_list);

        setClickListener();

        refreshData();
    }


    private void refreshData(){
        bundle = getIntent().getExtras();

        CourseSign courseSign = (CourseSign) bundle.getSerializable(ModelFieldConstants.COURSE_SIGN);
        System.out.println("CourseSignIn:courseSign = " + courseSign);
        String courseName = courseSign.getCourseName();
        String courseAddr = courseSign.getCourseAddr();
        long courseCreateTimeStamp = courseSign.getCreateTime();
        courseSignId = courseSign.getUserSignId();
        courseId = courseSign.getCourseId();

        tvCreateTimeMsg.setText(CommonUtils.stampToDate(String.valueOf(courseCreateTimeStamp), "yyyy-MM-dd hh:mm:ss"));
        tvSignAddressMsg.setText(courseAddr);
        tvCourseName.setText(courseName);

        courseHasSignedList = new ArrayList<>();
        adapter = new StuCourseSignedAdapter(
                CourseSignIn.this,
                R.layout.item_stu_signed,
                courseHasSignedList,
                0
        );
        LinearLayoutManager llm = new LinearLayoutManager(CourseSignIn.this);
        rvStuCourseList.setLayoutManager(llm);
        rvStuCourseList.setAdapter(adapter);

    }

    private void setClickListener(){
        abIvTitle.setOnClickListener(v -> finish());
        //点击签到后的事件
        btSign.setOnClickListener(v -> {
            @SuppressLint("InflateParams")
            View view = LayoutInflater.from(CourseSignIn.this).inflate(R.layout.dialog_input, null);
            //添加取消
            //添加"Yes"按钮
            @SuppressLint("NotifyDataSetChanged")
            AlertDialog.Builder builder = new AlertDialog.Builder(CourseSignIn.this)
                    .setMessage("请输入签到口令")
                    .setView(view)
                    .setPositiveButton("确定", (dialogInterface, i) -> {
                        etCodeInput = view.findViewById(R.id.et_code_input);
                        Editable etSignCode = etCodeInput.getText();
                        if(etSignCode == null){
                            Toast.makeText(CourseSignIn.this, "口令为空", Toast.LENGTH_SHORT).show();
                        }else{
                            signCodeStr = etSignCode.toString();
                            int signCode;
                            StuSignRequest stuSignRequest = new StuSignRequest();
                            stuSignRequest.setUserSignId(courseSignId);
                            stuSignRequest.setUserId(bundle.getLong(ModelFieldConstants.ID));
                            try{
                                signCode = Integer.parseInt(signCodeStr);
                                stuSignRequest.setSignCode(signCode);
                                signHandler = new Handler(msg -> {
                                    if(msg.arg1 == -1){
                                        String errorMsg = (String) msg.obj;
                                        Toast.makeText(CourseSignIn.this, errorMsg, Toast.LENGTH_SHORT).show();
                                    }else if(msg.arg1 == 1){
                                        Toast.makeText(CourseSignIn.this, "签到成功", Toast.LENGTH_SHORT).show();
                                        tvSignRecord.setVisibility(View.VISIBLE);
                                        getSignedHandler = new Handler(msg1 -> {
                                            if(msg1.arg1 == 1){
                                                adapter.notifyDataSetChanged();
                                            }
                                            return false;
                                        });
                                        getHasSignedList();
                                    }
                                    return false;
                                });
                                signIn(stuSignRequest);
                            }catch ( NumberFormatException numberFormatException){
                                Toast.makeText(CourseSignIn.this, "口令输入错误", Toast.LENGTH_SHORT).show();
                            }
                        }
                    })
                    .setNegativeButton("取消", (dialogInterface, i) -> {
                    })
                    .setNeutralButton("扫码", (dialog, which) -> {
                        // 创建IntentIntegrator对象
                        IntentIntegrator intentIntegrator = new IntentIntegrator(CourseSignIn.this)
                                .setBeepEnabled(true) //扫描提示音
                                .setPrompt("这是个扫码签到界面")
                                //.setCaptureActivity(MyCaptureActivity.class) //修改扫码活动
                                .setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)// 扫码的类型,可选：一维码，二维码，一/二维码
                                .setTimeout(10000);//15秒未扫描，则将自动关闭扫码界面
                        // 开始扫描
                        intentIntegrator.initiateScan();
                    });
            AlertDialog alertDialog2 = builder.create();
            alertDialog2.show();
        });
    }

    /**
     * 获取已选课程待签到内容
     */
    private void getHasSignedList(){
        new Thread(() -> {
            bundle = getIntent().getExtras();
            String urlParam = ModelFieldConstants.COURSE_ID + "=" + courseId + "&" +
                    ModelFieldConstants.USER_ID + "=" + bundle.getLong(ModelFieldConstants.ID) + "&" +
                    ModelFieldConstants.COURSE_SIGN_STATUS + "=" + 1 + "&" +
                    "current=1&size=10";
            String url = UrlConstants.STUDENT_SIGN_LIST + "?" + urlParam;
            new GetUrlParamHttpUtils() {
                @Override
                public void nextMethod(BaseResponse<Object> baseResponse) {
                    if(baseResponse.getData() != null){
                        System.out.println("StuClassListFragment:courseDataBaseResponse.getData() = " + baseResponse.getData() + "...............");

                        //解析数据
                        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
                        Object obj = baseResponse.getData();
                        LinkedTreeMap<String, String> courseDataMap = null;
                        if(obj instanceof LinkedTreeMap){
                            courseDataMap = (LinkedTreeMap<String, String>) obj;
                        }
                        //将LinkedTreeMap中字段映射到CourseData类中
                        //array:学生获取所选课程签到列表返回实体
                        String jsonString = gson.toJson(courseDataMap);
                        CourseData<CourseSign> courseData = gson.fromJson(jsonString, new TypeToken<CourseData<CourseSign>>() {}.getType());

                        if(courseData.getRecords().size() != 0){
                            courseHasSignedList.addAll(courseData.getRecords());
                            System.out.println("Here.............................");
                            Message message = new Message();
                            message.arg1 = 1;
                            getSignedHandler.sendMessage(message);
                        }
                    }
                }
                @Override
                public void failedMethod(BaseResponse<Object> baseResponse) { }
            }.getConnect(url);
        }).start();
    }

    /**
     * 学生签到
     * @param stuSignRequest 封装好的学生签到请求
     */
    private void signIn(StuSignRequest stuSignRequest){
        new Thread(() -> {
            System.out.println( "CourseSignIn:stuSignRequest : " + stuSignRequest.toString());
            String json = JSON.toJSONString(stuSignRequest);
            String url = UrlConstants.STUDENT_SIGN;

            new PostBodyParamHttpUtils() {
                @Override
                public void nextMethod(BaseResponse<Object> baseResponse) {
                    Message message = new Message();
                    message.arg1 = 1;
                    signHandler.sendMessage(message);
                }
                @Override
                public void failedMethod(BaseResponse<Object> baseResponse) {
                    Message message = new Message();
                    message.arg1 = -1;
                    message.obj = baseResponse.getMsg();
                    signHandler.sendMessage(message);
                }
            }.postConnect(url, json);
        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 获取解析结果
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "取消扫描", Toast.LENGTH_LONG).show();
            } else {
                String signCodeStr = result.getContents();
                int signCode;
                StuSignRequest stuSignRequest = new StuSignRequest();
                stuSignRequest.setUserSignId(courseSignId);
                stuSignRequest.setUserId(bundle.getLong(ModelFieldConstants.ID));
                try{
                    signCode = Integer.parseInt(signCodeStr);
                    stuSignRequest.setSignCode(signCode);
                    signHandler = new Handler(msg -> {
                        if(msg.arg1 == -1){
                            String errorMsg = (String) msg.obj;
                            Toast.makeText(CourseSignIn.this, errorMsg, Toast.LENGTH_SHORT).show();
                        }else if(msg.arg1 == 1){
                            Toast.makeText(CourseSignIn.this, "签到成功", Toast.LENGTH_SHORT).show();
                            tvSignRecord.setVisibility(View.VISIBLE);
                            getSignedHandler = new Handler(msg1 -> {
                                if(msg1.arg1 == 1){
                                    adapter.notifyDataSetChanged();
                                }
                                return false;
                            });
                            getHasSignedList();
                        }
                        return false;
                    });
                    signIn(stuSignRequest);
                }catch ( NumberFormatException numberFormatException){
                    Toast.makeText(CourseSignIn.this, "口令输入错误", Toast.LENGTH_SHORT).show();
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}